<?php

namespace app\controllers\h5\uni;

use app\controllers\h5\base\H5Controller;
use app\models\marketing\MarketingGroup;
use app\models\product\Product;
use app\models\product\ProductAreaList;
use app\models\product\ProductCategory;
use app\models\system\SetSwiper;
use app\redis\Cache;

/**
 * Class GroupController
 * @package app\controllers\h5\uni
 */
class GroupController extends H5Controller
{
    public function actionIndex()
    {
        $cache = Cache::get(Cache::$PAGE_GROUP);

        if (!$cache) {
            $data = [
                'swiper' => $this->swiper(),
                'category' => $this->category(),
                'quantity' => $this->getCount()
            ];

            Cache::set(Cache::$PAGE_GROUP, json_encode($data));
        } else {
            $data = json_decode($cache, true);
        }

        return $this->successEncode($data);
    }

    private function swiper()
    {
        return SetSwiper::find()
            ->where(['status' => SetSwiper::$statusMapping['OK']])
            // 拼团的轮播图
            ->andWhere(['category_id' => 2])
            ->orderBy(['sort' => SORT_ASC, 'id' => SORT_DESC])
            ->with(['image'])
            // ->select(['id', 'image_id'])
            ->asArray()
            ->all();
    }

    private function category()
    {
        // group area
        $area = 5;

        $ids = ProductAreaList::find()
            ->where(['area_id' => $area])
            ->select(['product_id'])
            ->column();

        $category_ids = Product::find()
            ->where(['id' => $ids])
            ->andWhere(['status' => Product::$statusMapping['OK']])
            ->select(['category_id'])
            ->column();

        return ProductCategory::find()
            ->where(['id' => $category_ids])
            ->asArray()
            ->all();
    }

    private function getCount()
    {
        $set = MarketingGroup::getLastOne();

        return $set->quantity;
    }
}